<template>
  <view class="table-form-container" :class="{ 'hidden-tool-bar-container': !isShowToolBarContainer }">
    <view class="table-content-box">
      <view v-show="isShowToolBarContainer" class="toolbar-buttons-container">
        <ToolBarBtns
          ref="toolbarRef"
          :tool-bar-config="toolBarConfig"
          :is-tree-table="isTreeTable"
          :table-body-data="tableBodyData"
          :flatten-table-body-data="flattenTableBodyData"
          @do-operation="onDoOperation"
        ></ToolBarBtns>
        <view class="search-form-container">
          <SceneContainerSearchForm
            :common-attr="searchFormCommonAttr"
            :form-item-meta-list="searchFormItemMetaList"
            :form-data="searchFormData"
            :search-form-item-dynmic-config-list="searchFormItemDynmicConfigList"
          >
            <template #searchBtn>
              <GdButton type="primary" @click="onSearch">
                <GdIcon :icon-name="'search'"></GdIcon>
              </GdButton>
            </template>
          </SceneContainerSearchForm>
        </view>
      </view>
      <view :style="{ height: computedTableContentContainerHeight }">
        <vxe-table
          ref="vxeTableRef"
          class="customize-table-container"
          :header-row-class-name="'customize-table-header'"
          :data="tableBodyData"
          height="auto"
          auto-resize
          :border="true"
          :expand-config="computedExpandConfig"
          :tree-config="computedTreeTableConfig"
          :checkbox-config="computedCheckboxConfig"
          :row-config="computedRowConfig"
          :column-config="computedColumnConfig"
          show-overflow="title"
          :keep-source="true"
          :edit-config="computedEditConfig"
          @checkbox-all="onCheckboxAll"
          @checkbox-change="onCheckboxChange"
          @cell-click="onCellClick"
          @current-change="onActiveCurrentRow"
        >
          <TableBody
            ref="tableBodyRef"
            :table-common-attr="tableCommonAttr"
            :table-body-data="tableBodyData"
            :flatten-table-body-data="flattenTableBodyData"
            :table-col-meta-list="tableColMetaList"
            :operation-btns-config="operationBtnsConfig"
            :is-tree-table="isTreeTable"
            :edit-config="computedEditConfig"
            :table-cell-submit-config="computedTableCellSubmitConfig"
            :table-column-dynmic-config-list="tableColumnDynmicConfigList"
            :cell-force-meta-config-mapping="cellForceMetaConfigMapping"
            :ancestor-table-common-attr="ancestorTableCommonAttr"

            @do-operation="onDoOperation"
            @remove-table-row="onRemoveTableRow"
            v-bind="$attrs"
            @checkbox-change="onChildCheckboxChange"
          ></TableBody>
          <!-- <template #empty>
          <text v-if="tableBodyData.length === 0">数据为空</text>
        </template> -->
        </vxe-table>
        <gd-button v-if="isShowBuildInAddRow" round size="small" type="primary" @click="onClickInlineEditableAddBtn">
          <gd-icon :icon-name="'plus'"></gd-icon>
        </gd-button>
        <!-- -->
        <el-pagination
          v-if="tableCommonAttr?.isPaged ?? false"
          class="pagination-container"
          v-model:currentPage="tableCommonAttr.paginationConfig.pageObj.pageNum"
          v-model:page-size="tableCommonAttr.paginationConfig.pageObj.pageSize"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableCommonAttr.paginationConfig.pageObj.totalCount"
          @size-change="onSizeChange"
          @current-change="onCurrentChange"
        ></el-pagination>
      </view>
    </view>
    <BtnEmitForm
      :all-btns-emit-form-item-meta-config="allBtnsEmitFormItemMetaConfig"
      :operation-event-params="operationEventParams"
      @do-operation="onDoOperation"
      :cur-picked-row-ids="curPickedRowIds"
      :table-body-data="tableBodyData"
      :flatten-table-body-data="flattenTableBodyData"
      :key-field="computedRowConfig.keyField"
      :parent-key-field="computedRowConfig.parentKeyField"
      :pagination-config="tableCommonAttr.paginationConfig.pageObj"
      :dialog-form-item-dynmic-config-list="dialogFormItemDynmicConfigList"
      :table-common-attr="tableCommonAttr"
      :cell-force-meta-config-mapping="cellForceMetaConfigMapping"
    ></BtnEmitForm>
  </view>
</template>
<script setup>
  import GdIcon from "@gd-accbuild-ui/gd-ui/gd-icon/gd-icon.vue";
  import GdButton from "@gd-accbuild-ui/gd-ui/gd-button/gd-button.vue";
  import SceneContainerSearchForm from "@gd-accbuild-ui/scene-container/scene-container-search-form/scene-container-search-form.vue";
  import ToolBarBtns from "./components/toolbar-btns/index.vue";
  import TableBody from "./components/table-body/index.vue";
  import BtnEmitForm from "./components/btn-emit-form/index.vue";
  import { getRandom, cloneDeep } from "@gd-accbuild-core/config/utils";
  import { util_GetFlattenTree } from "@gd-accbuild-ui/gd-ui/utils";

  import {
    useComputedExpandConfig,
    useComputedTreeTableConfig,
    useComputedCheckboxConfig,
    useComputedRowConfig,
    useComputedColumnConfig,
    useComputedEditConfig,
  } from "./hooks/useConfigTrans";
  import useMountTableOperation from "./hooks/useMountTableOperation";
  import useDynmicTableSize from "./hooks/useDynmicTableSize";
  import { ElPagination } from "element-plus";
  import "element-plus/theme-chalk/el-pagination.css";
  import "vxe-table/lib/style.css";
  import { onMounted, reactive, ref, computed, watch, inject, provide, shallowRef, getCurrentInstance } from "vue";
  import { useStore } from "@gd-accbuild-core/store/hackVueStore";
  //import XEUtils from "xe-utils";
  //import "xe-utils";

  const props = defineProps({
    tableLoading: {
      type: Boolean,
      default: true,
    },
    searchFormCommonAttr: {
      type: Object,
    },
    searchFormItemMetaList: {
      type: Array,
      default: () => [{}],
    },
    searchFormData: {
      type: Object,
      default: () => ({}),
    },
    tableCommonAttr: {
      type: Object,
      default: () => ({}),
    },
    tableColMetaList: {
      type: Array,
      default: () => [],
    },
    tableBodyData: {
      type: Array,
      default: () => [],
    },
    toolBarConfig: {
      type: Object,
    },
    operationBtnsConfig: {
      type: Object,
    },
    allBtnsEmitFormItemMetaConfig: {
      type: Object,
    },
    //////////
    searchFormItemDynmicConfigList: {
      type: Array,
    },
    dialogFormItemDynmicConfigList: {
      type: Array,
    },
    tableColumnDynmicConfigList: {
      type: Array,
    },
    ///////////
    ancestorTableCommonAttr: {
      type: Object,
    },
  });
  console.log(props, "这里可以222");
  const onSizeChange = () => {};
  const onCurrentChange = (num) => {};
  const computedExpandConfig = useComputedExpandConfig(props);
  const computedTreeTableConfig = useComputedTreeTableConfig(props);
  const isTreeTable = computed(() => computedTreeTableConfig.value.lazy);
  const computedCheckboxConfig = useComputedCheckboxConfig(props);
  const computedRowConfig = useComputedRowConfig(props);
  const computedEditConfig = useComputedEditConfig(props);
  const computedColumnConfig = useComputedColumnConfig(props);
  const flattenTableBodyData = computed(() => {
    if (props.tableCommonAttr.hasOwnProperty("treeTableConfig")) {
      return util_GetFlattenTree(props.tableBodyData);
    } else {
      return props.tableBodyData;
    }
  });
  // 表格高度动态响应 开始
  const {
    computedTableWidth,
    computedTableContentContainerHeight,
    computedTableFormContainerHeight,
    isInlineEditable,
    isShowBuildInAddRow,
    isShowToolBarContainer,
  } = useDynmicTableSize(props);

  // 表格高度动态响应 结束
  const toolbarRef = ref(null);
  const vxeTableRef = ref(null);
  const tableBodyRef = ref(null);
  const tableOperationMethods = reactive({});
  provide("tableOperationMethods", tableOperationMethods);

  useMountTableOperation(tableOperationMethods, vxeTableRef, props, flattenTableBodyData);

  let { proxy: vm } = getCurrentInstance();
  const operationEventParams = ref({});

  provide("vxeTableRef", vxeTableRef);

  const onDoOperation = (params) => {
    //console.log(params, "点击啦");
    operationEventParams.value = params;
  };

  const curPickedRowIds = reactive([]);
  const onCheckboxAll = (params) => {
    const rowid = computedRowConfig.value["keyField"];
    const rowids = props.tableBodyData.map((el) => el[rowid]);
    let resRowIds = [];
    if (params.checked) {
      resRowIds = rowids.filter((id) => !curPickedRowIds.includes(id));
      curPickedRowIds.push(...resRowIds);
    } else {
      rowids.forEach((el) => {
        const matchedIdx = curPickedRowIds.findIndex((pickedId) => pickedId === el);
        if (matchedIdx !== -1) {
          curPickedRowIds.splice(matchedIdx, 1);
        }
      });
    }
  };
  const onCheckboxChange = (params) => {
    const curPickedRows = vxeTableRef.value.getCheckboxRecords(true);
    curPickedRowIds.splice(0, curPickedRowIds.length);
    curPickedRows.forEach((row) => {
      curPickedRowIds.push(row.id);
    });

    emits("checkboxChange", {
      ...params,
      tableCommonAttr: props.tableCommonAttr,
    });
  };

  const onChildCheckboxChange = (params) => {
    emits("checkboxChange", params);
  };
  const emits = defineEmits(["tableCellClick", "activeCurrentRow", "rowEditUpdateTableData", "checkboxChange"]);
  const onCellClick = (params) => {
    emits("tableCellClick", {
      metaItem: props.tableColMetaList[params.rowIndex],
      metaItemList: props.tableColMetaList,
      commonAttr: props.tableCommonAttr,
      rowIdx: params.rowIndex,
      colIdx: params.columnIndex,
      rowData: params.row,
      tableBodyData: props.tableBodyData,
      formData: null,
    });
  };
  const tablePageReq = inject("tablePageReq", () => {});

  const onActiveCurrentRow = (params) => {
    emits("activeCurrentRow", {
      metaItem: props.tableColMetaList[params.rowIndex],
      metaItemList: props.tableColMetaList,
      commonAttr: props.tableCommonAttr,
      rowIdx: params.rowIndex,
      colIdx: params.columnIndex,
      rowData: params.row,
      tableBodyData: props.tableBodyData,
      formData: null,
    });
  };

  const onSearch = () => {
    tablePageReq();
  };

  const cellForceMetaConfigMapping = reactive({});
  const onClickInlineEditableAddBtn = () => {
    const matchedBtnConfig = toolbarRef.value.allBtnsConfig.find((btnConfig) => btnConfig.key === "buildInAddBtn");
    if (matchedBtnConfig) {
      onDoOperation({
        metaKey: matchedBtnConfig.key,
        containerAttr: matchedBtnConfig.containerAttr,
        metaItem: matchedBtnConfig,
        rowIdx: props.tableBodyData.length,
        rowData: { id: `_gd_id_${getRandom()}` },
      });
    }
  };
  /**
   * 不用记忆行状态信息的可以简单用这个方法更新
   */
  const onRemoveTableRow = ({ rowData, rowIdx }) => {
    const tableRowBtnsConfig = tableBodyRef.value.operationBtnsRef.allBtnsConfig;
    const matchedBtnConfig = tableRowBtnsConfig.find((btnConfig) => btnConfig.key === "buildInRowDeleteBtn");
    if (matchedBtnConfig) {
      onDoOperation({
        metaKey: matchedBtnConfig.key,
        containerAttr: matchedBtnConfig.containerAttr,
        metaItem: matchedBtnConfig,
        rowIdx: rowIdx,
        rowData: rowData,
      });
    }
    /* if (props.tableCommonAttr?.dataFromType) {
    //TODO:发送删除行请求
    if (props.tableCommonAttr.dataFromType === "VmCode") {
    }
  }
  tableOperationMethods.remove(rowData); */
  };
  const computedTableCellSubmitConfig = computed(() => {
    const btnConfig = props.toolBarConfig.buttons.find((btn) => btn.key === "buildInAddBtn");
    //props.tableCommonAttr?.editConfig?.editableStyle
    if (btnConfig) {
      return {
        submitStyle: computedEditConfig.value.submitStyle,
        allowAutoSubmit: computedEditConfig.value.submitStyle === "Auto",
        vmCode: btnConfig.vmCode,
        moduleCode: btnConfig.moduleCode
      };
    } else {
      return {
        submitStyle: "Manual",
      };
    }
  });

  defineExpose({
    tableRef: vxeTableRef,
    tableOperationMethods,
    computedTableContentContainerHeight,
  });
</script>
<style lang="scss" scoped>
  .table-form-container {
    height: v-bind("computedTableFormContainerHeight");
    /* height: calc(
    100vh - #{$--accbuild-page-top-window-container-height} - #{$--accbuild-page-tags-container-height} -
      2 * #{$--accbuild-default-container-gutter}
  ); */
    //margin: #{$--accbuild-default-container-gutter};
    background-color: #fff;
  }

  .toolbar-buttons-container {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: #{$--accbuild-toolbar-height-default};
    padding: #{$--accbuild-default-container-gutter} 0;
    //border-bottom: 0.5px solid #767980;
  }

  .hidden-tool-bar-container .toolbar-buttons-container {
    display: none;
  }

  .search-form-container {
    display: flex;
    justify-content: flex-end;
    width: 40%;
    min-width: 450px;
  }

  .table-content-box {
    margin: 0 #{$--accbuild-default-container-gutter};
    width: calc(v-bind(computedTableWidth));
    height: 100%;
    //width: calc(100% - 2 * #{$--accbuild-default-container-gutter});
  }

  .table-content-box :deep(div.vxe-grid--pager-wrapper) {
    min-width: 100%;
    width: 100%;
  }

  /* .table-content-box .customize-table-container {
  min-width: 100%;
  .vxe-table {
    min-width: 100%;
  }
} */

  /*滚动条整体部分*/
  .table-form-container ::-webkit-scrollbar {
    width: 10px;
    height: 10px;
  }

  /*滚动条的轨道*/
  .table-form-container ::-webkit-scrollbar-track {
    background-color: #ffffff;
  }

  /*滚动条里面的小方块，能向上向下移动*/
  .table-form-container ::-webkit-scrollbar-thumb {
    background-color: #bfbfbf;
    border-radius: 5px;
    border: 1px solid #f1f1f1;
    box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
  }

  .table-form-container ::-webkit-scrollbar-thumb:hover {
    background-color: #a8a8a8;
  }

  .table-form-container ::-webkit-scrollbar-thumb:active {
    background-color: #787878;
  }

  /*边角，即两个滚动条的交汇处*/
  .mytable-scrollbar ::-webkit-scrollbar-corner {
    background-color: #ffffff;
  }

  /* 表格样式 */
  .table-form-container :deep(.vxe-table.vxe-table--render-default) {
    z-index: 0;
  }

  /* 表头样式 */
  .customize-table-container :deep(.vxe-header--column .vxe-cell .vxe-cell--title) {
    color: #767980;
  }

  /* 分页样式 */
  .table-form-container .pagination-container {
    padding-left: calc((100% - 480px) / 2);
    margin: #{$--accbuild-default-container-gutter} 0 #{$--accbuild-default-container-gutter} 0;
  }

  .table-form-container .pagination-container .btn-prev,
  .table-form-container .pagination-container .btn-next {
    border: none;
  }

  ::v-global(i.customize-right-arrow) {
    display: inline-block;
    position: relative;
    width: 36rpx;
    height: 36rpx;
    margin-right: 20rpx;
  }

  ::v-global(i.customize-right-arrow::after) {
    display: inline-block;
    content: " ";
    height: 14rpx;
    width: 14rpx;
    border-width: 4rpx 4rpx 0 0;
    border-color: #c7c7cc;
    border-style: solid;
    transform: matrix(0.71, 0.71, -0.71, 0.71, 0, 0);
    position: absolute;
    top: 50%;
    right: 6rpx;
    margin-top: -9rpx;
  }

  ::v-global(.customize-down-arrow) {
    display: inline-block;
    position: relative;
    width: 40rpx;
    height: 30rpx;
    margin-right: 20rpx;
  }

  ::v-global(.customize-down-arrow::after) {
    display: inline-block;
    content: " ";
    height: 14rpx;
    width: 14rpx;
    border-width: 0 2rpx 2rpx 0;
    border-color: #999999;
    border-style: solid;
    transform: matrix(0.71, 0.71, -0.71, 0.71, 0, 0);
    transform-origin: center;
    transition: transform 0.3s;
    position: absolute;
    top: 50%;
    right: 10rpx;
    margin-top: -10rpx;
  }
</style>
